#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <taskLib.h>
#include "SimUdpFunc.h"
#include "../coreip/arpa/inet.h"


#define SEND_PORT_1	(8602)
#define SEND_PORT_2	(8603)
#define SEND_IP		"192.168.1.80"

int 			iTimerTaskId;
UDP_MESSAGE_T   g_udpInf[2];

void timer_handler(timer_t timerId, int arg)
{
	WriteUdpFuncImplement(&g_udpInf[0]);
}
void timer_handler2(timer_t timerId, int arg)
{
	WriteUdpFuncImplement(&g_udpInf[1]);
}

int init_timer(void)
{
	int iRetval;
	timer_t timer1Id, timer2Id;
	struct itimerspec timer_spec;

	iRetval = timer_create(CLOCK_REALTIME, NULL, &timer1Id);
	iRetval = timer_create(CLOCK_REALTIME, NULL, &timer2Id);
	if (iRetval == ERROR)
	{
		printf("timer create failed\n");
		return -1;
	}
	iRetval = timer_connect(timer1Id, timer_handler, 4567);
	iRetval = timer_connect(timer2Id, timer_handler2, 789);
	if (iRetval == ERROR)
	{
		printf("timer connect failed\n");
		return -1;
	}
	timer_spec.it_value.tv_sec = 2;
	timer_spec.it_value.tv_nsec = 0;
	timer_spec.it_interval.tv_sec = 0;
	timer_spec.it_interval.tv_nsec = 40 * 1000 * 1000;
	iRetval = timer_settime(timer1Id, 0, &timer_spec, NULL);
	if (iRetval == ERROR)
	{
		printf("set timer failed\n");
		return -1;
	}
	timer_spec.it_value.tv_sec = 2;
	timer_spec.it_value.tv_nsec = 0;
	timer_spec.it_interval.tv_sec = 0;
	timer_spec.it_interval.tv_nsec = 20 * 1000 * 1000;
	iRetval = timer_settime(timer2Id, 0, &timer_spec, NULL);
	if (iRetval == ERROR)
	{
		printf("set timer failed\n");
		return -1;
	}
	return 0;
}

void timer_task()
{
	
	printf("timer task tid = %X\n", taskIdSelf());
	init_timer();
	while (1)
	{
		taskDelay(60);
	}
}
int testmain(int a, int b, int c)
{
	int i = 0; 
	
	printf("a=%d b=%d c=%d\n",a,b,c);
	printf("testmain tid = %X\n", taskIdSelf());
	
	InitializeUdp();
	
	
	memset(g_udpInf,0,sizeof(UDP_MESSAGE_T));
	g_udpInf[0].port = SEND_PORT_1;
	g_udpInf[0].ip = inet_addr(SEND_IP);
	g_udpInf[0].buffLength = 100;
	g_udpInf[0].buff = malloc(100);
	
	g_udpInf[1].port = SEND_PORT_2;
	g_udpInf[1].ip = inet_addr(SEND_IP);
	g_udpInf[1].buffLength = 100;
	g_udpInf[1].buff = malloc(100);
	
	for(i = 0; i < 100; i++)
	{
		g_udpInf[0].buff[i] = i+1;
		g_udpInf[1].buff[i] = i+10;
	}
	
	iTimerTaskId = taskSpawn("TimerOpr", 210, 0, 4096, (FUNCPTR)timer_task, 0,0,0,0,0,0,0,0,0,0);
	
	return 0;
}
